<?php

// [ 路由类 ]

namespace core;

class Route
{
    private static $_route = [
        // 模块
        'module'   => '',
        // 资源
        'resource' => '',
        // 方法
        'method'   => '',
    ];

    public static function init()
    {
        if ( isset($_SERVER['REQUEST_URI']) ) {
            $pattern = strpos($_SERVER['REQUEST_URI'],'?') ? '/\/(.*)\?/U' : '/\/(.*)/';
            preg_match($pattern, $_SERVER['REQUEST_URI'], $uri);
            $pattern = strpos($uri[1], '/') ? '/\/(.*)/' : '/(.*)/';
            preg_match($pattern, $uri[1], $uri);
            $arr = explode('.', $uri[1]);
            if ( 2 == count($arr) ) {
                // 资源 + 方法
                self::$_route['resource'] = isset($arr[0]) ? strtolower($arr[0]) : '';
                self::$_route['method']   = isset($arr[1]) ? ucfirst($arr[1]) : '';
            } elseif ( 3 == count($arr) ) {
                // 模块 + 资源 + 方法
                self::$_route['module']   = isset($arr[0]) ? strtolower($arr[0]) : '';
                self::$_route['resource'] = isset($arr[1]) ? strtolower($arr[1]) : '';
                self::$_route['method']   = isset($arr[2]) ? ucfirst($arr[2]) : '';
            }
        }
    }

    public static function get($name = '')
    {
        return empty($name) ? self::$_route : ( isset(self::$_route[$name]) ? self::$_route[$name] : null );
    }

    public static function set($name, $value)
    {
        self::$_route[$name] = $value;
    }
}
